package info.emamian.droplet.controllers;

import info.emamian.droplet.aws.SQSService;
import info.emamian.droplet.data.DynamoDbSms;
import info.emamian.droplet.data.DynamoDbSmsService;
import info.emamian.droplet.provider.TwilioAdaptor;
import info.emamian.droplet.provider.InputSMSAdaptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/sms")
public class SMSController {
	private static final Logger logger = LoggerFactory.getLogger(SMSController.class);

	@Autowired
	DynamoDbSmsService dynamoDbSmsService;

	@Autowired
	SQSService sqsService;

	@Autowired
	TwilioAdaptor twilioAdaptor;

	@RequestMapping("/twilio")
	public void twilioRequestHandler(HttpServletRequest req, HttpServletResponse resp) {
		handleRequest(req, resp, twilioAdaptor);
	}

	private void handleRequest(HttpServletRequest req, HttpServletResponse resp, InputSMSAdaptor InputSMSAdaptor) {

		try {
			if (InputSMSAdaptor == null) { throw new Exception("inputSmsAdaptor cannot be null"); }
			DynamoDbSms converted = InputSMSAdaptor.convertToDynamoDbSMS(req);
			dynamoDbSmsService.save(converted);
			addToInputQueue(converted);
			resp.getWriter().write("done and done");
			resp.setStatus(HttpStatus.OK.value());
		}
		catch (Exception e) {
			logger.error("Exception handling request , ", e);
			resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());// 500
		}
	}

	private void addToInputQueue(DynamoDbSms converted) {
		try {
			sqsService.sendMessage(converted.getId());
		}
		catch (Exception e) {
			logger.error("Exception sending Message, ", e);
		}
	}

}
